package pers.wwz.study.spriingcloudfeign.servicea.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static pers.wwz.study.spriingcloudfeign.servicea.constant.Constants.LOGIN_TOKEN;

/**
 * feign拦截器
 *
 * @author wangwenzhe
 * @CreateDate 2024/03/24 23:9
 */
@Slf4j
@Component
@SuppressWarnings("unused")
public class FeignClientRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes !=null){
            HttpServletRequest request = attributes.getRequest();
            String authHeaderValue = request.getHeader(LOGIN_TOKEN);
            if (StringUtils.hasText(authHeaderValue)) {
                requestTemplate.header(LOGIN_TOKEN, authHeaderValue);
            }

        }

    }
}

